<template>
  <div v-if="show" class="fixed inset-0 z-50">
    <!-- 背景遮罩 -->
    <div class="absolute inset-0 bg-black bg-opacity-50" @click="close"></div>

    <!-- 评论面板 -->
    <div class="comment-panel absolute bottom-0 left-0 right-0 bg-white flex flex-col pb-[50px]" style="height: 75vh">
      <!-- 面板头部 -->
      <div class="comment-panel-header flex items-center justify-between py-2 px-4 border-b border-gray-200 relative">
        <!-- 顶部指示条 -->
        <div class="absolute top-2 left-1/2 transform -translate-x-1/2 w-8 h-1 bg-gray-300 rounded-full"></div>
        <h3 class="text-lg font-medium text-gray-900">{{ commentData.pagination?.total }} 条评论</h3>
        <button @click="close" class="p-2 hover:bg-gray-100 rounded-full transition-colors">
          <i class="fas fa-times text-gray-600"></i>
        </button>
      </div>

      <!-- 评论列表 -->
      <div class="flex-1 overflow-y-auto p-4 space-y-4">
        <div v-if="commentData.pagination?.total === 0" class="text-center py-8 text-gray-500">
          <i class="fas fa-comment text-4xl mb-4 text-gray-300"></i>
          <p>暂无评论，快来抢沙发吧！</p>
        </div>

        <div v-else v-for="comment in commentData.comments" :key="comment.id" class="flex space-x-3">
          <!-- 用户头像 -->
          <div class="flex-shrink-0">
            <img :src="comment.avatar" :alt="comment.user" class="w-10 h-10 rounded-full object-cover" />
          </div>

          <!-- 评论内容 -->
          <div class="flex-1 min-w-0">
            <div class="flex items-center space-x-2 mb-1">
              <span class="font-medium text-gray-900 text-sm">
                {{ comment.user }}
              </span>
              <span class="text-xs text-gray-400">
                {{ formatTime(comment.timestamp) }}
              </span>
            </div>
            <p class="text-gray-700 text-sm leading-relaxed">
              {{ comment.content }}
            </p>

            <!-- 评论操作 -->
            <div class="flex items-center space-x-4 mt-2">
              <button
                @click="toggleCommentLike(comment)"
                class="flex items-center space-x-1 text-xs transition-colors"
                :class="comment.isLiked ? 'text-red-500' : 'text-gray-400 hover:text-red-500'"
              >
                <i class="fas" :class="comment.isLiked ? 'fa-heart' : 'fa-heart'"></i>
                <span>{{ comment.likeCount || 0 }}</span>
              </button>
              <button class="text-xs text-gray-400 hover:text-gray-600 transition-colors">
                <i class="fas fa-reply"></i>
                回复
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 评论输入框 -->
      <div class="border-t border-gray-200 py-2 px-4 bg-white">
        <div class="flex items-center space-x-3">
          <input
            v-model="newComment"
            type="text"
            placeholder="写下你的想法..."
            class="flex-1 px-4 py-2 border border-gray-300 rounded-full text-sm text-gray-900 bg-white focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
            @keyup.enter="submitComment"
          />
          <button
            @click="submitComment"
            :disabled="!newComment.trim()"
            class="px-4 py-2 bg-red-500 text-white text-sm font-medium rounded-full transition-colors disabled:bg-gray-300 disabled:cursor-not-allowed hover:bg-red-600"
          >
            发表
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reqEpisodeComments, reqToggleCommentLike } from '@/apis/video'
import { useUserStore } from '@/stores/user'

import { formatTime, formatDateTime } from '@/utils/fotmatTime'

import { storeToRefs } from 'pinia'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  videoId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['close', 'comment-submitted'])

const commentData = ref({})
const newComment = ref('')

// 加载评论
const loadComments = async () => {
  try {
    const response = await reqEpisodeComments(props.videoId)
    console.log('评论数据:', response.data)

    commentData.value = response.data
  } catch (error) {
    console.error('加载评论失败:', error)
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) return

  try {
    const myComment = {
      user: userInfo.value.baseInfo.nickname, // 应该从用户状态获取
      avatar: userInfo.value.baseInfo.avatar,
      content: newComment.value,
      timestamp: formatDateTime(new Date())
    }

    // 添加到评论列表顶部
    commentData.value.comments.unshift(myComment)

    // 触发父组件的评论提交事件
    emit('comment-submitted', {
      videoId: props.videoId,
      comment: myComment
    })
  } catch (error) {
    console.error('提交评论失败:', error)
  }
}

// 切换评论点赞
const toggleCommentLike = async (comment) => {
  comment.isLiked = !comment.isLiked
  comment.likeCount += comment.isLiked ? 1 : -1

  const action = comment.isLiked ? 'like' : 'unlike'
  const response = await reqToggleCommentLike(comment.id, action)
  console.log('评论点赞接口响应:', response.data)
}

// 关闭评论面板
const close = () => {
  emit('close')
}

// 监听显示状态变化
watch(
  () => props.show,
  (show) => {
    if (show) {
      loadComments()
      // 防止背景滚动
      document.body.style.overflow = 'hidden'
    } else {
      // 恢复背景滚动
      document.body.style.overflow = 'auto'
    }
  }
)

// 组件挂载时加载评论
onMounted(() => {
  if (props.show) {
    loadComments()
    // 防止背景滚动
    document.body.style.overflow = 'hidden'
  }
})
</script>

<style scoped>
/* 动画效果 */
.fixed {
  animation: slideUp 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}

/* 底部弹框动画 */
@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

/* 圆角顶部 */
.comment-panel {
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15);
}

/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 4px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 优化移动端体验 */
@media (max-width: 640px) {
  .comment-panel {
    height: 80vh !important;
  }
}

/* 防止背景滚动 */
body.overflow-hidden {
  overflow: hidden;
  position: fixed;
  width: 100%;
  height: 100%;
}

/* 确保输入框文字可见 */
input[type='text'] {
  color: #111827 !important; /* 深灰色 */
  background-color: #ffffff !important; /* 白色背景 */
}

/* 聚焦时保持可见性 */
input[type='text']:focus {
  color: #111827 !important;
  background-color: #ffffff !important;
}
</style>
